const next = require('next')
const Koa = require('koa')
// const logger = require('koa-logger')
const Router = require('koa-router')
const proxy = require('koa-server-http-proxy')

const port = parseInt(process.env.PORT, 10) || 8000
const dev = process.env.NODE_ENV !== 'production'
// const test = process.env.NODE_TEST === 'test';
const urlType = process.env.NODE_URL;
const nextApp = next({ dev });
const handler = nextApp.getRequestHandler();
// 页面路由
const serverRouter = require('./server/router');
var axios = require('axios')
let proxyUrl = 'https://index-api.meadin.com';
switch(urlType) {
  case "dev": 
    // proxyUrl = "http://10.10.29.251:8081";
    proxyUrl = "http://10.10.29.246:8081";
    break;
  case "test":
    proxyUrl = "http://10.10.29.205:6300";
    break;
  default:
    break;
}
console.log(`NODE_ENV: ${process.env.NODE_ENV}`);
console.log(`NODE_URL: ${process.env.NODE_URL}`);
console.log(`NODE_CND: ${process.env.NODE_CND}`);
console.log(`koaServerProxy: ${proxyUrl}`);
const proxyTable = {
  '/openapi/': {
    // target: dev ? proxyUrl : (test ? 'http://10.10.29.205:6300' : 'https://index-api.meadin.com'),
    target: proxyUrl,
    changeOrigin: true
  },
   '/tourism/': {
    // target: dev ? proxyUrl : (test ? 'http://10.10.29.205:6300' : 'https://index-api.meadin.com'),
    target: proxyUrl,
    changeOrigin: true
  },
  '/connect': {
    target: 'https://open.weixin.qq.com',
    changeOrigin: true
  }
}
nextApp.prepare()
  .then(() => {
    const server = new Koa()
    const router = new Router();
    // server.use(logger())
    // if (dev && proxyTable) {
    if (proxyTable) {
      Object.keys(proxyTable).forEach((context) => {
        server.use(proxy(context, proxyTable[context]))
      })
    }
    
    server.use(serverRouter(nextApp).routes());
    server.use(router.allowedMethods());
    // router.all('(.*)', async (ctx) => {
    //   await handler(ctx.req, ctx.res)
    //   ctx.respond = false
    // })

    server.use(async (ctx, next) => {
      await handler(ctx.req, ctx.res)
      ctx.respond = false
      // await next()
    })
    // server.use(async (ctx, next) => {
    //   console.log(ctx);
    //   ctx.res.statusCode = 200
    //   await next()
    // })
    // server.use(router.routes());
    server.use(async (ctx, next) => {
      ctx.res.statusCode = 200
      await next()
    })
    server.listen(port, (err) => {
      if (err) throw err
      console.info(`> Ready on http://localhost:${port}`)
    })
  })
